import React, { /*ChangeEvent,*/ useId } from 'react';
import { InlineField, Input, Select, Stack, TextArea } from '@grafana/ui';
import { QueryEditorProps } from '@grafana/data';
import { DataSource } from '../datasource';
import { MyDataSourceOptions, MyQuery, OBSQueryType } from '../types';
import { useShadowedState } from './hooks/useShadowedState';
import { DEFAULT_RESULT_FORMAT, RESULT_FORMATS } from '../constants';

type Props = QueryEditorProps<DataSource, MyQuery, MyDataSourceOptions>;

export function QueryEditor({ query, onChange, onRunQuery }: Props) {
  const [currentQuery, setCurrentQuery] = useShadowedState(query.query);
  const [currentAlias, setCurrentAlias] = useShadowedState(query.alias);
  const aliasElementId = useId();
  const selectElementId = useId();
  const resultFormat = query.resultFormat ?? DEFAULT_RESULT_FORMAT;

  if (!query.obsQueryType || !query.rawQuery) {
    onChange({
      ...query,
      obsQueryType: OBSQueryType.Buckets,
      rawQuery: true,
      resultFormat,
    });
    onRunQuery();
  }

  /*const obsQueryTypeMap: Record<OBSQueryType, SelectableValue<OBSQueryType>> = {
    [OBSQueryType.Buckets]: {
      label: 'Buckets',
      value: OBSQueryType.Buckets,
      description: 'Query bucket list.',
    },
    [OBSQueryType.Storage]: {
      label: 'Storage',
      value: OBSQueryType.Storage,
      description: 'Query storage usage.',
    },
    [OBSQueryType.Cost]: {
      // TODO
      label: 'Cost',
      value: OBSQueryType.Cost,
      description: 'Query cost fee.',
    },
  };*/

  /*const obsQueryTypes: Array<SelectableValue<OBSQueryType>> = [
    obsQueryTypeMap[OBSQueryType.Buckets],
    obsQueryTypeMap[OBSQueryType.Storage],
    obsQueryTypeMap[OBSQueryType.Cost],
  ];*/

  const applyDelayedChangesAndRunQuery = () => {
    onChange({
      ...query,
      query: currentQuery,
      alias: currentAlias,
      resultFormat,
    });
    onRunQuery();
  };

  /*const onOBSQueryTypeChange = (selected: SelectableValue<OBSQueryType>) => {
    onChange({
      ...query,
      obsQueryType: selected.value,
      resultFormat,
    });
    onRunQuery();
  };*/

  return (
    <Stack gap={0}>
      {/*{channel === 0 && (
        <InlineField>
          <Select
            aria-label="Query Type"
            className="width-30"
            value={query.obsQueryType ?? OBSQueryType.Buckets}
            options={obsQueryTypes}
            defaultValue={obsQueryTypeMap[OBSQueryType.Buckets]}
            onChange={onOBSQueryTypeChange}
          />
        </InlineField>
      )}*/}
      <Stack direction={'column'}>
        <TextArea
          aria-label="query"
          rows={3}
          spellCheck={false}
          placeholder="InfluxDB Query"
          onBlur={applyDelayedChangesAndRunQuery}
          onChange={(e) => {
            setCurrentQuery(e.currentTarget.value);
          }}
          value={currentQuery ?? ''}
        />
        <Stack>
          <InlineField htmlFor={selectElementId} label="Format as">
            <Select
              inputId={selectElementId}
              onChange={(v) => {
                onChange({ ...query, resultFormat: v.value });
                onRunQuery();
              }}
              value={resultFormat}
              options={RESULT_FORMATS}
            />
          </InlineField>
          <InlineField htmlFor={aliasElementId} label="Alias by">
            <Input
              id={aliasElementId}
              type="text"
              spellCheck={false}
              placeholder="Naming pattern"
              onBlur={applyDelayedChangesAndRunQuery}
              onChange={(e) => {
                setCurrentAlias(e.currentTarget.value);
              }}
              value={currentAlias ?? ''}
            />
          </InlineField>
        </Stack>
      </Stack>
    </Stack>
  );
}
